/**
 * 描述: {描述}
 * 作者: jack-song
 * 创建日期: 2017/11/5 22:42
 * 修改日期: 2017/11/5 22:42
 * 版本: {版本}
 */
package com.easy.component.component.bander;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;


import com.easy.component.R;
import com.easy.component.component.bander.model.AdResult;
import com.easy.component.component.bander.transformer.ScaleAlphaPageTransformer;

import java.util.List;

public class BanderView extends LinearLayout {

    /**
     * 上下文
     */
    private Context mContext;

    /**
     * 图片轮播视图
     */
    private ViewPager mBannerPager;
    /**
     * 滚动图片视图适配器
     */
    private ImageCycleAdapter mAdvAdapter;
    /**
     * 当前第几个
     */
    private int indexPostion = 0;
    /**
     * 图片滚动时间
     */
    private int timeInterval = 1000 * 5;
    /**
     * 广告轮播
     */
    private Handler mHandler = new Handler();

    /**
     * @param context
     */
    public BanderView(Context context) {
        super(context);
    }

    /**
     * @param context
     * @param attrs
     */
    @SuppressLint("ClickableViewAccessibility")
    public BanderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.view_banner_content, this);
        mBannerPager = findViewById(R.id.pager_banner);
        mBannerPager.setPageTransformer(true, new ScaleAlphaPageTransformer());
        mBannerPager.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        // 开始图片滚动
                        startImageTimerTask();
                        break;
                    default:
                        // 停止图片滚动
                        stopImageTimerTask();
                        break;
                }
                return false;
            }
        });
    }

    /**
     * @param infoList
     * @param imageCycleViewListener
     */
    @SuppressWarnings("unused")
    public void setImageResources(final List<AdResult> infoList, ImageCycleViewListener imageCycleViewListener) {
        indexPostion = 0;
        stopImageTimerTask();
        mBannerPager.addOnPageChangeListener(new BanderPageChangeListener(infoList, imageCycleViewListener));
        mAdvAdapter = new ImageCycleAdapter(mContext, infoList, imageCycleViewListener);
        mBannerPager.setAdapter(mAdvAdapter);
        mAdvAdapter.notifyDataSetChanged();
        startImageTimerTask();
    }

    /**
     * 〈一句话功能简述〉<br>
     * 〈轮播图片状态监听器〉
     *
     * @author
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本] （可选）
     */
    private final class BanderPageChangeListener implements ViewPager.OnPageChangeListener {

        private ImageCycleViewListener imageCycleViewListener;
        private List<AdResult> adList;

        public BanderPageChangeListener(List<AdResult> adList, ImageCycleViewListener imageCycleViewListener) {
            this.imageCycleViewListener = imageCycleViewListener;
            this.adList = adList;
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_IDLE)
                startImageTimerTask();
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int index) {
            imageCycleViewListener.onSelectItem(adList, index % adList.size());
            indexPostion = index;
        }

    }

    /**
     * 开始图片滚动任务
     */
    private void startImageTimerTask() {
        stopImageTimerTask();
        // 图片每8秒滚动一次
        mHandler.postDelayed(mImageTimerTask, timeInterval);
    }

    /**
     * 停止图片滚动任务
     */
    private void stopImageTimerTask() {
        mHandler.removeCallbacks(mImageTimerTask);
    }

    /**
     * 图片自动轮播Task
     */
    private Runnable mImageTimerTask = new Runnable() {
        @Override
        public void run() {
            int postion = ++indexPostion;
            mBannerPager.setCurrentItem(postion);
        }
    };

    /**
     * 〈一句话功能简述〉<br>
     * 〈ViewPager适配器〉
     *
     * @author
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本] （可选）
     */
    private class ImageCycleAdapter extends PagerAdapter {
        /**
         * 图片资源列表
         */
        private List<AdResult> mAdList;

        /**
         * 广告图片点击监听器
         */
        private ImageCycleViewListener mImageCycleViewListener;

        private Context mContext;

        public ImageCycleAdapter(Context context, List<AdResult> adList, ImageCycleViewListener imageCycleViewListener) {
            mContext = context;
            mAdList = adList;
            mImageCycleViewListener = imageCycleViewListener;
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }
        @Override
        public float getPageWidth(int position) {
            return (float) 0.7;
        }


        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == obj;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            final int adListPosition = position % mAdList.size();
            View view = LayoutInflater.from(mContext).inflate(R.layout.easy_item_bander, null);
            Object imageUrl = mAdList.get(adListPosition).getAdUrl();
            ImageView imageView = view.findViewById(R.id.iv_bander);
            LinearLayout linearLayout = view.findViewById(R.id.ll_bander);
//            if (mAdList.get(adListPosition).isChecked()) {
//                linearLayout.setBackgroundResource(R.drawable.shape_bander_home_ffa0775e_bg);
//                Log.e("yes", mAdList.get(adListPosition).isChecked() + "--" + adListPosition);
//            } else {
//                linearLayout.setBackgroundResource(R.drawable.shape_bander_home_transparent_bg);
//                Log.e("no", mAdList.get(adListPosition).isChecked() + "" + adListPosition);
//            }
            // 设置图片点击监听
            imageView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    mImageCycleViewListener.onImageClick(mAdList.get(adListPosition), adListPosition, v);
                }
            });
            mImageCycleViewListener.displayImage(mAdList.get(position % mAdList.size()).getData(), imageUrl, imageView);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            View view = (View) object;
            container.removeView(view);
        }

    }

    /**
     * 〈一句话功能简述〉<br>
     * 〈轮播控件的监听事件〉
     *
     * @author jack-song
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本] （可选）
     */
    public interface ImageCycleViewListener {

        /**
         * 功能描述: <br>
         * 〈加载图片资源〉
         *
         * @param imageURL
         * @param imageView
         * @see [相关类/方法](可选)
         * @since [产品/模块版本](可选)
         */
        void displayImage(Object data, Object imageURL, ImageView imageView);

        /**
         * 功能描述: <br>
         * 〈单击图片事件〉
         *
         * @param info
         * @param postion
         * @param imageView
         * @see [相关类/方法](可选)
         * @since [产品/模块版本](可选)
         */
        void onImageClick(AdResult info, int postion, View imageView);

        void onSelectItem(List<AdResult> info, int index);
    }

}
